package com.net.entity;

import com.tank.entrity.Tank;
import com.tank.model.GameModel;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.UUID;

@Data
@Slf4j
@ToString
@EqualsAndHashCode(callSuper = true)
public class TankStopMessage extends Message {
    private UUID id;
    private int x, y;
    public TankStopMessage(Tank t) {
        this.id = t.getUuid();
        this.x = (int) t.getX();
        this.y = (int) t.getY();
    }

    public TankStopMessage(UUID id, int x, int y) {
        this.id = id;
        this.x = x;
        this.y = y;
    }

    public TankStopMessage() {}
    @Override
    public void handle() {
        if (this.id.equals(((Tank) GameModel.getInstance().getMainTank()).getUuid())) {
            return;
        }
        Tank tank = (Tank) GameModel.getInstance().findTankByUUID(this.id);
        if (tank != null) {
            tank.setMoving(false);
            tank.setX(this.x);
            tank.setY(this.y);
        }
    }

    @Override
    @SneakyThrows
    public byte[] toBytes() {
        @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();
        @Cleanup DataOutputStream dos = new DataOutputStream(baos);
        dos.writeLong(id.getMostSignificantBits());
        dos.writeLong(id.getLeastSignificantBits());
        dos.writeInt(x);
        dos.writeInt(y);
        dos.flush();
        return baos.toByteArray();
    }

    @Override
    @SneakyThrows
    public void parse(byte[] bytes) {
        @Cleanup DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
        this.id = new UUID(dis.readLong(), dis.readLong());
        this.x = dis.readInt();
        this.y = dis.readInt();
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.TankStop;
    }
}
